11. Navigation Based on State

L6 A11 Navigation Based On State

If the user is not logged in, it doesn’t make much sense for them to be able to set any customizations. In this step, you will add the code to navigate the user to the login screen if they attempt to access the settings screen when they are not logged in.

  1. In SettingsFragment.kt’s onViewCreated(), observe the authenticationState and redirect the user to LoginFragment if they are not authenticated.

SettingsFragment.kt

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
   super.onViewCreated(view, savedInstanceState)
   val navController = findNavController()
   viewModel.authenticationState.observe(viewLifecycleOwner, Observer { authenticationState ->
       when (authenticationState) {
           LoginViewModel.AuthenticationState.AUTHENTICATED -> Log.i(TAG, "Authenticated")
           // If the user is not logged in, they should not be able to set any preferences,
           // so navigate them to the login fragment
           LoginViewModel.AuthenticationState.UNAUTHENTICATED -> navController.navigate(
               R.id.loginFragment
           )
           else -> Log.e(
               TAG, "New $authenticationState state that doesn't require any UI change"
           )
       }
   })
}
  1. Since the app takes the user to the login screen if they try to access the settings screen, the app also needs to handle the back button behavior on the login screen. If the app doesn’t customize handling the back button behavior, the user would be stuck in an infinite loop of trying to go back to the Settings screen, but then be redirected to the login screen again.

    In LoginFragment.kt’s onViewCreated(), handle back button actions by bringing the user back to the MainFragment.

LoginFragment.kt

// If the user presses the back button, bring them back to the home screen
requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner) {
   navController.popBackStack(R.id.mainFragment, false)
}
  1. Relaunch your app and confirm that if you’re not logged in, attempts to access the Settings screen will now redirect you to the login flow. While you have successfully redirected the user to login, you haven’t handled what happens after the user successfully logs in, so attempts to login will appear is if it’s not working. You will fix this in the next step.